<template>
  <Form :model="drawer" :rules="ruleValidate" ref="validForm">
    <FormItem label="系统名" label-position="top" prop="sysName">
      <Input v-model="drawer.sysName" placeholder="请输入系统名称"/>
    </FormItem>

    <FormItem label="系统编码" label-position="top" prop="remark">
      <Input v-model="drawer.remark" placeholder="请输入系统编码"/>
    </FormItem>

    <FormItem label="系统接口前缀地址" label-position="top" prop="url">
      <Input v-model="drawer.url" placeholder="请输入系统接口前缀地址"/>
    </FormItem>

    <FormItem label="系统描述" label-position="top">
      <Input type="textarea" v-model="drawer.description" :rows="4" placeholder="请输入系统描述信息"/>
    </FormItem>

    <FormItem label="系统状态" label-position="top" prop="state">
      <Switch size="large" v-model="drawer.state">
        <template #open>
          <span>启用</span>
        </template>
        <template #close>
          <span>禁用</span>
        </template>
      </Switch>
    </FormItem>
  </Form>

  <div class="demo-drawer-footer">
    <Button style="margin-right: 8px" @click="$emit('close-win', false)">关闭</Button>
    <Button type="primary" @click="handlerForm">保存</Button>
  </div>
</template>

<script setup>

import {ref, reactive} from 'vue'

const props = defineProps({
  drawer: {
    type: Object,
    required: true
  }
});

const emits = defineEmits(["close-win"])

// 定义校验规则
const ruleValidate = reactive({
   sysName: [
     {required: true, message: "系统名不允许为空",  trigger: "blur"},
     {type: "string", max:"100", message: "系统名太长",  trigger: "blur"},
   ],
   url: [
     {type: "url", message: "系统地址前缀不是一个合法的网络地址", trigger: "blur"}
   ],
  state: [
    {type: "boolean", message: "状态必须是一个boolean类型的值", trigger: "blur"}
  ]
})

// 声明 form 组件
const validForm = ref(null) ;

function resetValidForm() {
  validForm.value.resetFields();
}

function handlerForm() {
   // 校验表单参数
  validForm.value.validate(valid => {
      if (valid) {
        if (props.drawer.id == null) {
          handlerSave() ;
        }else{
          handlerUpdate();
        }
      }
  })
}

// 处理保存逻辑
function handlerSave() {
  console.log("正在保存数据...");
  emits("close-win", "save");
}

// 处理更新逻辑
function handlerUpdate() {
  console.log("正在更新数据...")
  emits("close-win", "update");
}

// 将 resetValidForm 函数暴露给调用者
defineExpose({
  resetValidForm,
})
</script>

<style scoped>
.icon {
  vertical-align: middle;
  margin: 0 3px;;
}

.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>
